package room_event

import (
	"encoding/json"
	"fmt"
	"longmen/server/config/global"
	cache2 "longmen/server/internal/rpc/tencentim/cache"
	"longmen/server/internal/rpc/tencentim/config"
	"longmen/server/internal/rpc/tencentim/imsdk"
	messages2 "longmen/server/internal/rpc/tencentim/messages"
	"longmen/server/internal/rpc/tencentim/utils"
	"longmen/server/pkg/common/helper/blackWorlds"
	"longmen/server/pkg/common/helper/util"
	pb "longmen/server/pkg/protobuf"
	"strconv"
	"strings"
)

// AvChatGroupHandler 直播群处理
func AvChatGroupHandler(req *pb.CallbackReq) (*pb.CallbackResp, error) {
	switch req.GetCallbackCommand() {
	// 发言前回调
	case config.RoomBeforeMsg:
		if req.From_Account == "admin" { // 賽事發送ID
			return utils.CallbackOkResp(nil), nil
		}
		allMsg := req.GetMsgBody()
		for _, msg := range allMsg {
			switch msg.MsgType {
			// 普通文本消息
			case imsdk.TIM_MSG_TYPE_TEXT:
				return riskFilter(req, msg)
			// 腾讯其他消息
			case imsdk.TIM_MSG_TYPE_CUSTOM: // 其他类型
				bytes := []byte(msg.MsgContent.Data)

				if len(msg.MsgContent.Data) == 0 {
					bytes = []byte(msg.MsgContent.Text)
				}
				incomeMsg := messages2.IncomingMessage{}
				err := json.Unmarshal(bytes, &incomeMsg)
				if err != nil {
					global.Log.Errorf("%v,%s", err, "消息不能识别")
					return utils.CallbackFailResp(nil, "消息不能识别"), err
				}
				return AvaChatRoomHandler(req, &incomeMsg, bytes)
			}
		}
	case config.BeforeJoinRoom:
		global.Log.Debugf("IncrIpStats BeforeJoinRoom Msgbody:%+v,平台:%v", req.MsgBody, req.OptPlatform)
		roomId, _ := strconv.Atoi(req.GroupId)
		IncrIpStats(roomId, req.ClientIP)
		login, err := cache2.SetClientBeforeLogin(req)
		if err != nil {
			global.Log.Errorf("set login err: %v", err)
			return login, err
		}
		return &pb.CallbackResp{
			ActionStatus: "OK",
		}, nil

	case config.RoomAfterMsg:
		allMsg := req.GetMsgBody()
		for _, msg := range allMsg {
			switch msg.MsgType {
			case imsdk.TIM_MSG_TYPE_TEXT: //这里把聊天记录记起来
				return handlerHistory(req, msg)
			case imsdk.TIM_MSG_TYPE_CUSTOM: //这里存炫彩弹幕，彩色背景
				return handlerProps(req, msg)
			}
		}

	default:
		return nil, fmt.Errorf("unknown msg type: %s", req.GetCallbackCommand())
	}

	return utils.CallbackOkResp(""), nil
}

// 发言后处理(历史记录)
func handlerHistory(req *pb.CallbackReq, msg *pb.MsgBody) (ret *pb.CallbackResp, errorRes error) {

	text := msg.MsgContent.Text
	global.Log.Debugf("历史记录消息类型%+v", msg)
	//文字消息进历史
	if len(text) > 0 {
		adminText := text
		if strings.Contains(adminText, "*") {
			adminText = text + "(" + cache2.GetFilterdMsg(req.GroupId, req.From_Account) + ")"
		}
		return HandlingAfterMessage(req, text, adminText, "")
	} else {
		return utils.CallbackOkResp(nil), nil
	}

}

// 道具（炫彩弹幕等）消息进历史
func handlerProps(req *pb.CallbackReq, msg *pb.MsgBody) (ret *pb.CallbackResp, errorRes error) {
	text := msg.MsgContent.Data
	if len(msg.MsgContent.Data) == 0 { //不能为空
		return &pb.CallbackResp{
			ActionStatus: "OK",
			ErrorCode:    0,
		}, nil
	}

	inMsg := messages2.IncomingMessageWithContent{}
	err := json.Unmarshal([]byte(text), &inMsg)
	if err == nil { //解开成功
		if *inMsg.Type == messages2.PropsMessageType {
			return HandlingAfterMessage(req, *inMsg.Content, *inMsg.Content, text)
		} else {
			global.Log.Debugf("type:%s,after消息未处理%v", *inMsg.Type, req)
		}
	} else {
		global.Log.Debugf("%s,%s|%v", "after消息识别出错", err.Error(), req)
	}
	return &pb.CallbackResp{
		ActionStatus: "OK",
		ErrorCode:    0,
	}, nil
}

// 发言前处理
func riskFilter(req *pb.CallbackReq, msg *pb.MsgBody) (ret *pb.CallbackResp, err error) {
	global.Log.Infof("riskFilter:%+v\n", req)
	user, err := GetUser(req)
	if err != nil {
		ret = &pb.CallbackResp{
			ActionStatus: "OK",
			ErrorCode:    10177,
			ErrorInfo:    "",
		}
		return ret, err
	}
	replace := msg.MsgContent.Text
	//bReplaced := false
	if user.Role != 3 { //房管不改消息，可以随便发
		b := util.ContainsLink(msg.MsgContent.Text)
		if b {
			ret = &pb.CallbackResp{
				ActionStatus: "OK",
				ErrorCode:    10178,
				ErrorInfo:    "内容含有敏感词",
			}
			return ret, err
		}
		replace = blackWorlds.BlackWorInstance.ReplaceWithAsterisk(msg.MsgContent.Text)
		if strings.Contains(replace, "*") {
			_ = cache2.PutFilteredMsg(req.GroupId, req.From_Account, msg.MsgContent.Text)
		}
	}

	cloudData := messages2.SayMessageCloudData{}
	// 活动统计。暂时去掉
	/**
	var abid int
	err = global.GetR().Model(&models_main.ActivityBarrage{}).Where("status=1").Pluck("id", &abid).Error
	if err != nil {
		global.Log.Infof("Activity Error: %s", err.Error())
	}
	var liveID int64
	roomID, _ := strconv.Atoi(req.GroupId)
	if roomID == 0 {
		roomID = user.RoomId * 100
	}
	err = global.Live().Model(&models_live.Live{}).Where("anchorid=?", roomID/100).Pluck("liveid", &liveID).Error
	if err != nil {
		global.Log.Infof("Activity Stat Error: %s", err.Error())
	}
	key := fmt.Sprintf("ACTIVITY_STAT_%d_%d_%d", roomID, abid, liveID)
	rets, _ := global.GetRds().HGetAll(key).Result()
	cloudData.ActivitySum = len(rets) **/

	_ = json.Unmarshal([]byte(req.CloudCustomData), &cloudData)
	sayExt := messages2.SayMessageExtend{
		Level:               user.Level,
		Role:                user.Role,
		Vip:                 user.Vip,
		SayMessageCloudData: cloudData,
	}
	marshal, err := json.Marshal(sayExt)
	if err != nil {
		ret = &pb.CallbackResp{
			ActionStatus: "OK",
			ErrorCode:    10177,
			ErrorInfo:    "内容无法发送",
		}
		return ret, err
	}

	return utils.OkRespText(replace, string(marshal)), nil
}
